package processes;

import java.util.ArrayList;
import java.util.Queue;

import factory.Observed;
import factory.ObserverManager;
import to.OrderTO;
import to.ProductTO;
import util.ProductParser;

public abstract class MachineManager implements Observed {
	private ObserverManager observer;
	private ArrayList<Machine> machineList = new ArrayList();
	private ArrayList<OrderTO> orderList = new ArrayList();
	private int manufacturedAmount;

	public MachineManager() {
		observer = ObserverManager.getInstance(); 
	}
	
	public void notifyOrder(OrderTO order){
		if(!orderList.contains(order)){
			orderList.add(order);
		}
		deployWork();
	}
	
	public void notifyFinishedOrder(OrderTO order) {
		orderList.remove(order);
	}
	
	public void notifyDeploy(){
		deployWork();
	}
	
	private void deployWork(){
		for(int i=0; i<=machineList.size()-1; i++){
			Machine machine = machineList.get(i);
			if(machine.getWork()==null){
orderLoop:		for(int j=0; j<=orderList.size()-1; j++){
					OrderTO order = orderList.get(j);
					for(int k=0; k<=order.getProductList().size()-1; k++){
						if(ProductParser.getInstance().existFile(getDir(), order.getProductList().get(k).getProductId())){
							machine.addWork(order);
							break orderLoop;
						}
					}
				}
			}
		}
	}
	
	public void update(OrderTO order){
		observer.notifyOrder(order);
	}
	
	public void addMachine(Machine machine){
		machineList.add(machine);
	}
	
	public ArrayList<Machine> getMachineList(){
		return machineList;
	}
	
	public abstract String getDir();
	public abstract String getNextDir();
}
